'''python3 code
author's email: chenyan@feling.net

测试httpd4t.py用的简易http客户端,可以发出简单的http POST请求

例：
python3 client.py /signup username=name password=123
'''
from urllib.request import Request, urlopen
from urllib import parse
from urllib.error import HTTPError, URLError
import sys
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%M:%S')


domain = 'http://localhost:8888/UserAction!'

uri = sys.argv[1]

data_dic = {}

for i in range(2,len(sys.argv)):
    kv = sys.argv[i].split('=')
    k = kv[0]
    v = kv[1]
    data_dic[k] = v

logging.debug(data_dic)

data = parse.urlencode(data_dic).encode('utf-8') 

req = Request(url=domain+uri, method='POST')

try:
    with urlopen(req, data) as res:
        res_code = str(res.code)
        res_str = res.read().decode('utf-8')
    logging.info(res_code+', '+res_str)
except HTTPError as e:
    logging.info(str(e.getcode())+', '+e.msg)
except URLError as e:
    logging.warning(e)
